package fun.boomcat.luckyhe.mirai.plugin.botcontrol.util;

import net.mamoe.mirai.Bot;
import net.mamoe.mirai.console.command.CommandManager;
import net.mamoe.mirai.console.command.CommandSender;
import net.mamoe.mirai.contact.*;
import net.mamoe.mirai.event.events.BotInvitedJoinGroupRequestEvent;
import net.mamoe.mirai.event.events.MemberJoinRequestEvent;
import net.mamoe.mirai.event.events.NewFriendRequestEvent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class BotUtil {

    public static void pageSender(CommandSender commandSender, String message) {
        int splitLength = 2000;
        int strLen = message.length();
        int totalPages = strLen / splitLength + (strLen % splitLength == 0 ? 0 : 1);

        StringBuilder sb = new StringBuilder(message);

        int current = 1;
        while (sb.length() != 0) {
            String part;
            try {
                part = sb.substring(0, splitLength);
                sb = new StringBuilder(sb.substring(splitLength, sb.length()));
            } catch (IndexOutOfBoundsException e) {
                part = sb.substring(0, sb.length());
                sb = new StringBuilder();
            }

            commandSender.sendMessage("<第" + current + "页，共" + totalPages + "页>\n" + part);
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                commandSender.sendMessage("错误：" + e.toString());
                return;
            }
            current++;
        }
    }

    public static boolean isOneBot() {
        List<Bot> instances = Bot.getInstances();
        return instances.size() <= 1;
    }

    public static Bot getBotInstance() {
        List<Bot> instances = Bot.getInstances();
        if (instances.size() != 0) {
            return instances.get(0);
        } else {
            return null;
        }
    }

    public static String getFriendsStr(ContactList<Friend> friends) {
        StringBuilder sb = new StringBuilder();
        sb.append("QQ号/昵称/remark\n");
        for (Friend friend : friends) {
            sb.append(getFriendLineStr(friend));
        }
        return sb.toString();
    }

    public static String getFriendLineStr(Friend friend) {
        return friend.getId() + "/" + friend.getNick() + "/" + friend.getRemark() + "\n";
    }

    public static String getGroupsStr(ContactList<Group> groups) {
        StringBuilder sb = new StringBuilder();
        sb.append("群号/群名\n");
        for (Group group : groups) {
            sb.append(getGroupLineStr(group));
        }
        return sb.toString();
    }

    public static String getGroupLineStr(Group group) {
        return group.getId() + "/" + group.getName() + "\n";
    }

    public static String getGroupMulLineStr(Group group, String primaryName) {
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();

        StringBuilder sb = new StringBuilder();
        sb.append("群号：").append(group.getId()).append("\n");
        sb.append("群名：").append(group.getName()).append("\n");
        sb.append("群头像：").append(group.getAvatarUrl()).append("\n");
        sb.append("群主QQ号：").append(group.getOwner().getId()).append("\n");
        sb.append("使用").append(commandPrefix).append(primaryName).append(" group ");
        sb.append(group.getId()).append(" help（别名：帮助）").append("    查看群操作帮助");
        return sb.toString();
    }

    public static String getFriendMulLineStr(Friend friend, String primaryName) {
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();

        StringBuilder sb = new StringBuilder();
        sb.append("好友QQ：").append(friend.getId()).append("\n");
        sb.append("昵称：").append(friend.getNick()).append("\n");
        sb.append("备注：").append(friend.getRemark()).append("\n");
        sb.append("头像：").append(friend.getAvatarUrl()).append("\n");
        sb.append("使用").append(commandPrefix).append(primaryName).append(" friend ");

        sb.append(friend.getId()).append(" help（别名：帮助）").append("    查看好友操作帮助");

        return sb.toString();
    }

    public static String getGroupMemberMulLineStr(NormalMember member, String primaryName) {
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();
        StringBuilder sb = new StringBuilder();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        sb.append("群号：").append(member.getGroup().getId()).append("\n");
        sb.append("QQ号：").append(member.getId()).append("\n");
        sb.append("昵称：").append(member.getNick()).append("\n");
        sb.append("头像：").append(member.getAvatarUrl()).append("\n");
        sb.append("群昵称：").append(member.getNameCard()).append("\n");
        sb.append("加入时间：").append(sdf.format(new Date(member.getJoinTimestamp() * 1000L))).append("\n");
        sb.append("上次发言：").append(sdf.format(new Date(member.getLastSpeakTimestamp() * 1000L))).append("\n");
        sb.append("剩余禁言时间：").append(member.getMuteTimeRemaining()).append("秒").append("\n");
        sb.append("群头衔：").append(member.getSpecialTitle()).append("\n");
        sb.append("在群身份：").append(member.getPermission()).append("\n");
        sb.append("使用").append(commandPrefix).append(primaryName).append(" group ");
        sb.append(member.getGroup().getId()).append(" member ").append(member.getId()).append(" help（别名：帮助）");
        sb.append("查看关于操作群成员的帮助");

        return sb.toString();
    }

    public static String getGroupMemberLineStr(NormalMember normalMember) {
        return normalMember.getId() + "/" + normalMember.getNameCard() + "/" + normalMember.getNick() + "\n";
    }

    public static String getGroupMembersStr(ContactList<NormalMember> members, Group group, String primaryName) {
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();

        StringBuilder sb = new StringBuilder();

        sb.append("QQ号/群昵称/个人昵称\n");
        for (NormalMember member : members) {
            sb.append(getGroupMemberLineStr(member));
        }
        sb.append("使用").append(commandPrefix).append(primaryName).append(" group ");
        sb.append(group.getId()).append(" member ").append("<群成员QQ号>").append("    查看群成员具体信息及群成员操作");
        return sb.toString();
    }

    public static String getGroupSettingsMulLineStr(GroupSettings settings, Group group, String primaryName) {
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();
        StringBuilder sb = new StringBuilder();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        sb.append("群号：").append(group.getId()).append("\n");
        sb.append("匿名聊天：").append(settings.isAnonymousChatEnabled()).append("\n");
        sb.append("自动加群审批：").append(settings.isAutoApproveEnabled()).append("\n");
        sb.append("1. 全体禁言：").append(settings.isMuteAll()).append("\n");
        sb.append("2. 允许邀请好友：").append(settings.isAllowMemberInvite()).append("\n");

        sb.append("使用").append(commandPrefix).append(primaryName).append(" group ");
        sb.append(group.getId()).append(" settings ").append("<上述编号>").append("    切换开关（即开变关，关变开）");

        return sb.toString();
    }

    public static String getEventStateMulStr(Set<Map.Entry<String, Boolean>> entries, String primaryName) {
        StringBuilder sb = new StringBuilder();
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();
        sb.append("事件：\n");

        int i = 0;
        for (Map.Entry<String, Boolean> entry : entries) {
            sb.append(i).append(". ").append(entry.getKey()).append(": ")
                    .append(entry.getValue()).append("\n");
            i++;
        }

        sb.append("使用").append(commandPrefix).append(primaryName).append(" event <编号> [[编号2]…]    修改事件通知状态");

        return sb.toString();
    }

    public static String getMessageEventGroupsMulStr(List<Long> groups, String primaryName) {
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();
        StringBuilder sb = new StringBuilder();

        sb.append("列表中有以下群：\n");
        for (long groupId : groups) {
            sb.append(groupId).append("\n");
        }
        sb.append(ControlCommandHelp.messageEventGroupHelp(primaryName));

        return sb.toString();
    }

    public static String getFriendRequestsMulStr(List<NewFriendRequestEvent> events, String primaryName) {
        StringBuilder sb = new StringBuilder();

        sb.append("事件号/QQ/昵称/来自群/原因\n");
        for (NewFriendRequestEvent event : events) {
            sb.append(event.getEventId()).append("/")
                    .append(event.getFromId()).append("/")
                    .append(event.getFromNick()).append("/")
                    .append(event.getFromGroupId()).append("/")
                    .append(event.getMessage()).append("\n");
        }

        sb.append(ControlCommandHelp.friendRequestHelp(primaryName));

        return sb.toString();
    }

    public static String getMemberJoinRequestMulStr(List<MemberJoinRequestEvent> events, String primaryName) {
         StringBuilder sb = new StringBuilder();

         sb.append("事件号/申请人QQ/昵称/群/群名\n");
         for (MemberJoinRequestEvent event : events) {
             sb.append(event.getEventId()).append("/")
                     .append(event.getFromId()).append("/")
                     .append(event.getFromNick()).append("/")
                     .append(event.getGroupId()).append("/")
                     .append(event.getGroupName()).append("\n");
         }

         sb.append(ControlCommandHelp.memberJoinRequestHelp(primaryName));

         return sb.toString();
    }

    public static String getBotInvitedJoinGroupRequest(List<BotInvitedJoinGroupRequestEvent> events, String primaryName) {
        StringBuilder sb = new StringBuilder();

        sb.append("事件号/群/群名/邀请人QQ/昵称\n");
        for (BotInvitedJoinGroupRequestEvent event : events) {
            sb.append(event.getEventId()).append("/")
                    .append(event.getGroupId()).append("/")
                    .append(event.getGroupName()).append("/")
                    .append(event.getInvitorId()).append("/")
                    .append(event.getInvitorNick()).append("\n");
        }

        sb.append(ControlCommandHelp.botInvitedJoinGroupRequestHelp(primaryName));

        return sb.toString();
    }
}
